package com.xunfang.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunfang.common.RedisConst;
import com.xunfang.portal.model.entity.Book;
import com.xunfang.portal.service.BookService;
import com.xunfang.portal.mapper.BookMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
* @author scott
* @description 针对表【t_book】的数据库操作Service实现
* @createDate 2025-10-10 09:20:56
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
    implements BookService{

    //查询
    @Override
    //添加缓存
    @Cacheable(cacheNames = RedisConst.BOOK_LIST, keyGenerator = "keyGenerator")
    public Page<Book> findTopSales(Integer pageNum, Integer pageSize) {

        //01 创建分页对象
        Page<Book> page = new Page<>(pageNum, pageSize);

        //02 调用方法
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = Wrappers.lambdaQuery(Book.class);
        bookLambdaQueryWrapper.orderByDesc(Book::getBuyCount);

        //分页查询
        page(page,bookLambdaQueryWrapper);
        //03 组装数据
        // data \ total

        //04 返回结果
        return page;

    }

    @Override
    public Page<Book> findByType(Integer pageNum, Integer pageSize, Integer typeId) {

        //01 创建分页对象
        Page<Book> page = new Page<>(pageNum, pageSize);

        //02 调用方法
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = Wrappers.lambdaQuery(Book.class);
        bookLambdaQueryWrapper.eq(Book::getTypeId, typeId);
        bookLambdaQueryWrapper.orderByDesc(Book::getUpdateTime);

        //分页查询
        page(page,bookLambdaQueryWrapper);

        return page;
    }

    /**
     *    RedisConst.BOOK_DETAIL= book:detail
     *   "#root.methodName 方法的名称
     *   #id 给的参数
     *   redis中: key = book:detail::findById::1
     * @param id
     * @return
     */

    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_DETAIL, key = "#root.methodName + ':' + #id")
    public Book findById(Long id) {

        Book book = getById(id);

        return book;

    }
}




